package pers.zhuli.weblog.service;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.secure.SaBase64Util;
import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Service;
import pers.zhuli.weblog.dao.ArticleDAO;
import pers.zhuli.weblog.entity.Article;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Service
public class ArticleService {
    @Resource
    private ArticleDAO articleDAO;

    public int addArticle(String json) {
        Article article = JSON.parseObject(json, Article.class);
        article.setContent(SaBase64Util.encode(article.getContent()));
        if (article.getId() == 0) {
            article.setCreateDatetime(new Date().toString());
        } else {
            article.setLastEditDatetime(new Date().toString());
        }
        try {
            article.setUserId(StpUtil.getLoginIdAsInt());
        } catch (NotLoginException e) {
            return 0;
        }
        try {
            articleDAO.save(article);
            return 1;
        } catch (Exception e) {
            return -1;
        }
    }

    public Article getArticle(int id) {
        try {
            Article article = articleDAO.findById(id);
            article.setContent(SaBase64Util.decode(article.getContent()));
            return article;
        } catch (Exception e) {
            return null;
        }
    }

    public List<Map<Integer, String>> getNewTop10() {
        return articleDAO._getNewTop(10);
    }

    public List<Map<Integer, String>> getHotTop10() {
        return articleDAO._getHotTop(10);
    }
}
